# -*- coding: utf-8 -*-
# !/usr/bin/python
__author__ = 'bitfeng'

import re
import six


def to_unicode(text, encoding=None, errors='strict'):
    """Return the unicode representation of a bytes object `text`. If `text`
    is already an unicode object, return it as-is."""
    if isinstance(text, six.text_type):
        return text
    if not isinstance(text, (bytes, six.text_type)):
        raise TypeError('to_unicode must receive a bytes, str or unicode '
                        'object, got %s' % type(text).__name__)
    if encoding is None:
        encoding = 'utf-8'
    return text.decode(encoding, errors)


def leave_chinese(keywords):
    data_string = to_unicode(keywords)
    if data_string and isinstance(data_string, unicode):
        return re.sub(u'[^\u4e00-\u9fa5\uff08\uff09]', u'', data_string)
    return ''


def length_limit(keywords, length=20):
    if isinstance(keywords, (str, unicode)):
        if len(keywords) <= 20:
            return to_unicode(keywords)
    return


def filter_keyword(keyword):
    try:
        return length_limit(leave_chinese(keyword))
    except Exception, e:
        print '[Error] filter_keyword(%s) [%s]' % (str(keyword), str(e))
    return


# class ServerParse(object):

if __name__ == '__main__':
    print filter_keyword('（？ＫＫＬＬＦ,,　？是的方式大家反而我））) a %')
    # print u'（）'
